#include "app_mqtt.h"
#include "log/log.h"
#include "MQTTClient.h"
#include "string.h"
//初始化mqtt客户端
//消息对象
static MQTTClient_message pubmsg = MQTTClient_message_initializer;//消息对象
static MQTTClient client; //客户端
//连接选项
static MQTTClient_connectOptions conn_opts = MQTTClient_connectOptions_initializer;//连接选项
//当收到远程消息时调用他
static int (*recv_callback)(char *json) = NULL;
//发送消息的回调函数
static void delivered(void *context, MQTTClient_deliveryToken dt)
{
    printf("发送消息成功");
}
 //收到远程消息的回调函数
 //1表示成功，0表示失败
 static int msgarrvd(void *context, char *topicName, int topicLen, MQTTClient_message *message)
{
    int result = 0;
    //判断回调函数是否为空
    if (recv_callback != NULL)
    {
     //调用回调函数，并返回结果
     result = recv_callback((char*)message->payload)==0 ? 1 : 0;
    }
    //释放内存
    MQTTClient_freeMessage(&message);
    MQTTClient_free(topicName);
    //返回结果
    return result;
}
 //连接断开时的回调函数
 static void connlost(void *context, char *cause)
{
    printf("断开原因: %s\n", cause);
}
//初始化mqtt客户端
int app_mqtt_init(void)
{
//创建客户端
if (MQTTClient_create(&client, ADDRESS, CLIENTID, MQTTCLIENT_PERSISTENCE_NONE, NULL) != 0)
{
    log_error("创建客户端失败");
    return -1;
}
//注册回调
if (MQTTClient_setCallbacks(client, NULL, connlost, msgarrvd, delivered) != 0)
{
    log_error("注册回调函数失败");
    //销毁客户端
    MQTTClient_destroy(&client);
    return -1;
}

//连接mqtt服务器
if (MQTTClient_connect(client, &conn_opts) != 0)
{
    log_error("连接mqtt服务器失败");
    //销毁客户端
    MQTTClient_destroy(&client);
    return -1;
}
//订阅主题
if (MQTTClient_subscribe(client, TOPIC_RTG, QOS) != 0)
{
    log_error("订阅主题失败");
    app_mqtt_close();//关闭客户端
    return -1;
}
return 0;

}
//关闭客户端
void app_mqtt_close(void)
{
MQTTClient_disconnect(client, TIMEOUT);//断开连接
MQTTClient_destroy(&client);//销毁客户端
}
//发布消息
int app_mqtt_send(char *json)
{
    pubmsg.payload = json;
    pubmsg.payloadlen = strlen(json);
    pubmsg.qos = QOS;//服务质量
    int result = MQTTClient_publishMessage(client, TOPIC_GTR, &pubmsg, NULL);
if (result != 0)
{
    log_error("发布消息失败");
    return -1;
}
return 0;

}
//注册接受处理消息的回调
void app_mqtt_regist_recv_cb(int (*cb)(char *json))
{
    recv_callback = cb;
}
